package validates

import (
	"github.com/go-playground/validator/v10"
	"regexp"
)

func init() {
	V.RegisterValidation("validatePasswd", validatePasswd)
	V.RegisterValidation("validateUsername", validateUsername)
}

//密码必须包含数字、字母、符号中至少两种
func validatePasswd(f1 validator.FieldLevel) bool {
	var (
		//种类数
		catagory int = 0
	)

	numRegx := regexp.MustCompile(`[0-9]`)
	alphaRegx := regexp.MustCompile(`[a-zA-Z]`)
	otherAsciiRegex := regexp.MustCompile(`[^0-9a-zA-Z]`)

	if numRegx.FindString(f1.Field().String()) != "" {
		catagory++
	}
	if alphaRegx.FindString(f1.Field().String()) != "" {
		catagory++
	}
	if otherAsciiRegex.FindString(f1.Field().String()) != "" {
		catagory++
	}
	//少于两种种类，失败
	if catagory < 2 {
		return false
	}
	return true
}

//用户名只能包含字母数字字符或单个连字符，不能以连字符开头或结尾(即必须以数字或字母开头或结尾)。
func validateUsername(f1 validator.FieldLevel) bool {
	username := f1.Field().String()

	reg1 := regexp.MustCompile("^[^0-9a-zA-Z]")
	reg2 := regexp.MustCompile("[^0-9a-zA-Z]$")
	if len(reg1.FindString(username)) != 0 {
		return false
	}
	if len(reg2.FindString(username)) != 0 {
		return false
	}
	return true
}
